package com.eastdigit.system.controller;

import com.eastdigit.servlet.DeptPermPrepare;
import com.eastdigit.servlet.ReqBean;
import com.eastdigit.servlet.RequestAttribute;
import com.eastdigit.servlet.Response;
import com.eastdigit.system.model.IDepartment;
import com.eastdigit.system.service.BaseTreeService;
import com.eastdigit.system.service.IDepartmentService;
import com.eastdigit.system.service.IPermissionService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller(value = "IDepartmentController")
@RequestMapping(value = "/department")
public class DepartmentController {

    @Autowired
    private IPermissionService permissionService;
    @Autowired
    private IDepartmentService departmentService;

    @RequestMapping(value = "/tree")
    @ResponseBody
    public JSONObject queryDepartmentTree(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        JSONArray array = new JSONArray();
        String userId = reqBean.getUserId();
        for (IDepartment department : permissionService.getAuthedDepartments(userId, reqBean.getMenuId(),
                reqBean.getInfo("parentDeptId"))) {
            array.add(department.toJSONObject());
        }
        return Response.response(array);
    }

    @RequestMapping(value = "/treeGrid")
    @ResponseBody
    @DeptPermPrepare(id = "deptId", deptId = "deptId")
    public JSONObject queryDepartmentTreeGrid(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        JSONArray array = new JSONArray();
        String userId = reqBean.getUserId();
        Map<String, JSONObject> map = new HashMap<String, JSONObject>();
        for (IDepartment department : permissionService.getAuthedDepartments(userId, reqBean.getMenuId(),
                reqBean.getInfo("parentDeptId"))) {
            JSONObject jsonObject = department.toJSONObject();
            array.add(jsonObject);
            map.put(jsonObject.getString("deptId"), array.getJSONObject(array.size() - 1));// 这里要注意，array中的对象不是同一个了
        }
        for (String deptId : map.keySet()) {
            JSONObject jsonObject = map.get(deptId);
            String parentDeptId = jsonObject.getString("parentDeptId");
            if (!map.containsKey(parentDeptId)) {
                IDepartment parent = departmentService.queryDepartment(parentDeptId);
                jsonObject.put("parentDeptName", parent == null ? parentDeptId : parent.getDeptName());
            }
        }
        return Response.response(BaseTreeService.queryTreeGridFlat("deptId", "parentDeptId", array));
    }

}
